﻿using JESAI.Core.Encryptor;
using JESAI.Core.Util.Helpers;
using JESAI.Core.Util.Http.Clients;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Platform.AutoUpdate
{
    //自动更新版本Worker
    public class AutoUpdateVersionWorker : BackgroundService
    {
        private readonly ILogger<AutoUpdateVersionWorker> _logger;
        private readonly IConfiguration _configuration;

        public AutoUpdateVersionWorker(ILogger<AutoUpdateVersionWorker> logger, IConfiguration configuration)
        {
            _logger= logger;
            _configuration= configuration;
        }
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("自动升级服务检查启动完成");
            while (!stoppingToken.IsCancellationRequested )
            {
                try
                {
                    var url = _configuration["AutoUpdate:CheckStatusUrl"];
                    HttpWebClient client = new HttpWebClient();
                    var appKey = _configuration["AutoUpdate:AppKey"];
                    var secret = _configuration["AutoUpdate:Secret"];
                    long currentTimeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

                    var token = AesEncryptor.Instance.Encrypt(currentTimeStamp.ToString(), secret);
                    try
                    {
                        var apiResult = client.Post(url).Header("AppKey", appKey).Header("Token", token).Result();
                        ApiResult apiResult1 = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                        if (apiResult1.Code == 1)
                        {
                            UpdateExcute();
                        }
                        else
                        {
                            _logger.LogInformation($"自动升级服务检查完成,当前正在采集中");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogException(ex);
                        //UpdateExcute();
                    }
                
                    Task.Delay(300000).Wait(); //五分钟检查一次。
                }
                catch (Exception ex)
                {
                    _logger.LogException(ex);
                }
            }

            return Task.CompletedTask;
        }

        private void UpdateExcute()
        {
            var host = _configuration["AutoUpdate:Host"];
            var username = _configuration["AutoUpdate:UserName"];
            var password = _configuration["AutoUpdate:Password"];
            var appname = _configuration["AutoUpdate:AppName"];
            var updatepath = _configuration["AutoUpdate:UpdatePath"];
            var versionLib = _configuration["AutoUpdate:VersionLib"];
            var appRootPath = AppDomain.CurrentDomain.BaseDirectory;

            var driveLetter = appRootPath.Split(":")[0];
            var updateCmd = $"{driveLetter}: & cd {appRootPath} & {appRootPath}JESAI.AutoUpdate.Exec.exe run -t {host} -u {username} -k {password} -p {updatepath} -l {versionLib} -f {appname}";
            var result = CmdHelper.Run(updateCmd);
            _logger.LogInformation($"执行自动更新检查完成-" + result);
        }
    }
}
